package myJs.cps

import myJs.api.Api
import myJs.myPkg.Lightbox
import myJs.myPkg.jquery.$
import myJs.tool.Tool
import org.scalajs.dom.{FileList, FileReader, html, window}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.useState
import slinky.core.facade.React
import slinky.web.html._
import typings.csstype.csstypeStrings

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}

/**
 * Created by yz on 21/1/2022
 */
@react object ImageViewCp {

  case class Props(id: String, images: List[String])

  val component = FunctionalComponent[Props] { props =>

    val (isOpen, setIsOpen) = useState(false)
    val (photoIndex, setPhotoIndex) = useState(0)

    val inputRef = React.createRef[html.Input]

    object FTool {

      def preview(curI: Int) = () => {
        setPhotoIndex(curI)
        setIsOpen(true)
      }

      def closeF = () => {
        setIsOpen(false)
      }

      def nextF(nextIndex: Int) = () => {
        setPhotoIndex(nextIndex)
      }

      def prevF(preIndex: Int) = () => {
        setPhotoIndex(preIndex)
      }

    }

    val images = props.images
    val imageUrls = props.images.map { image =>
      Tool.imageUrl(props.id, image)
    }

    div(style := Style(),
      if (images.nonEmpty) {
        images.zipWithIndex.map { case (uri, curI) =>
          div(key := s"${curI}", style := STool.imgDiv,
            div(style := STool.img(props.id, uri),
              onClick := FTool.preview(curI),
              className := "myImgDiv"
            )
          )
        }
      } else div(style := Style(paddingTop = 7), "未上传"),

      if (isOpen) {
        val nextIndex = (photoIndex + 1) % images.length
        val preIndex = (photoIndex + images.length - 1) % images.length
        Lightbox(mainSrc = imageUrls(photoIndex), nextSrc = imageUrls(nextIndex), prevSrc = imageUrls(preIndex),
          imageTitle = s"${photoIndex + 1}/${images.size}",
          onCloseRequest = FTool.closeF,
          onMoveNextRequest = FTool.nextF(nextIndex),
          onMovePrevRequest = FTool.prevF(preIndex)
        )()
      } else null

    )

  }

  object STool {

    val imgWidth = 150
    val imgHeight = 150

    val imgDiv = Style(backgroundRepeat = "no-repeat", backgroundSize = "cover",
     position=csstypeStrings.relative, display = csstypeStrings.`inline-block`, marginRight = 20)

    def img(id: String, fileName: String) = Style(backgroundImage = s"url('${Tool.imageUrl(id, s"thumb_${fileName}")}')",
      backgroundRepeat = "no-repeat",
      backgroundSize = "cover", width = imgWidth, height = imgHeight, border = "3 px solid #fff",
      boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem")

  }


}
